//
//  LYPictureFirstVC.m
//  LYCustomTransitionDemo
//
//  Created by liyang on 2017/12/5.
//  Copyright © 2017年 liyang. All rights reserved.
//

#import "LYPictureBrowserCell.h"
#import <SDWebImage/SDImageCache.h>
#import "DGActivityIndicatorView.h"
#import "GGProgressView.h"
//#import "UIImage+Extension.h"
#import "ICMediaManager.h"
#import "UIImage+QAExtension.h"
@interface LYPictureBrowserCell ()

@property (nonatomic, strong) DGActivityIndicatorView *aiView;

@property (nonatomic, strong) GGProgressView *progressView;

@property (nonatomic, strong) UIButton *lookOriginBtn;

@end

@implementation LYPictureBrowserCell

#pragma mark - Life cycle

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor blackColor];
        [self setupView];
    }
    return self;
}

- (void)setupView {
    [self.contentView addSubview:self.pictureImageScrollView];
//       添加滑动手势
   
    [self.pictureImageScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self);
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(-50);
        make.bottom.mas_equalTo(0);
    }];
//    [self.contentView addSubview:self.progressView];
    [self.contentView addSubview:self.lookOriginBtn];
}
- (void)dealloc{
    
}
#pragma mark - lazy

- (LYBrowseZoomScrollView *)pictureImageScrollView {
    if (!_pictureImageScrollView) {
        _pictureImageScrollView = [[LYBrowseZoomScrollView alloc]initWithFrame:CGRectMake(0, 0, self.size.width - 50, self.size.height)];
        _pictureImageScrollView.backgroundColor = [UIColor blackColor];
        _pictureImageScrollView.zoomScale = 1.0f;
//        _pictureImageScrollView.maximumZoomScale=3.0;//最大倍率（默认倍率）
//        _pictureImageScrollView.minimumZoomScale=1.0;//最小倍率（默认倍率）
//        _pictureImageScrollView.decelerationRate=1.0;//减速倍率（默认倍率
        __weak typeof(self)weakSelf = self;
        [_pictureImageScrollView setTapBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(imageViewClick:)]) {
                [weakSelf.delegate imageViewClick:weakSelf.cellIndex];
            }
        }];
    }
    return _pictureImageScrollView;
}

- (GGProgressView *)progressView {
    if (!_progressView) {
        _progressView = [GGProgressView new];
        //设置
        _progressView.progressTintColor = main_blue_color;
        _progressView.trackTintColor = assist_viewBg_color;
        _progressView.progress = 0.0;
        _progressView.progressViewStyle = GGProgressViewStyleTrackFillet;
        _progressView.hidden = YES;
    }
    return _progressView;
}

- (UIButton *)lookOriginBtn {
    if (!_lookOriginBtn) {
        _lookOriginBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2 - 60, SCREEN_HEIGHT - WCI_IPHONE_SAFEBOTTOMAREA_HEIGHT - 30 - 32, 120, 32)];
        [_lookOriginBtn setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.4]];
        [_lookOriginBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _lookOriginBtn.hidden = YES;
        ViewRadius(_lookOriginBtn, 5);
        [_lookOriginBtn addTarget:self action:@selector(downloadOriginImage:) forControlEvents:UIControlEventTouchUpInside];
        [_lookOriginBtn setTitle:(@"查看原图") forState:UIControlStateNormal];
        _lookOriginBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    }
    return _lookOriginBtn;
}

- (DGActivityIndicatorView *)aiView {
    if (!_aiView) {
        _aiView = [[DGActivityIndicatorView alloc] initWithType:DGActivityIndicatorAnimationTypeBallSpinFadeLoader tintColor:[UIColor whiteColor]];
        _aiView.frame = CGRectMake(SCREEN_WIDTH/2 - 20,SCREEN_HEIGHT/2 - 20, 40, 40);
        [self.contentView addSubview:_aiView];
        [self.contentView bringSubviewToFront:_aiView];
        _aiView.hidden = NO;
    }
    return _aiView;
}

#pragma mark - getter & setter

- (void)showWithModel:(LYPictureBrowseSouceModel *)model {
    self.model = model;

    UIImageView *imageView = _pictureImageScrollView.zoomImageView;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.clipsToBounds = YES;
    NSString * fileKey = model.msg ? model.msg.fileKey :model.imgUrl;
    UIImage * placeholderImage = model.image ?: [[ICMediaManager sharedManager] imageWithLocalPath:[[ICMediaManager sharedManager] imagePathWithFileKey:fileKey] andNetUrl:model.imgUrl isDown:NO];//  ;
    if (!placeholderImage) {
        placeholderImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:model.imgUrl];
        if (!placeholderImage) {
            placeholderImage = [UIImage imageNamed:@"new_img_loading"];
        }
    }else{
        model.image = placeholderImage;
    }
    BOOL isSend = model.msg ? model.msg.deliveryState == MPMessageDeliveryStateDelivered : YES;
    if (model.imgUrl.length == 0 && isSend) {
        placeholderImage = [UIImage imageNamed:@"album_ill_pic"];
        model.image = placeholderImage;
    }
    
    if (self.callBackToLoadImageEnd) {
        self.callBackToLoadImageEnd(placeholderImage, self.cellIndex);
    }
    
    imageView.image = placeholderImage;
    
    [self setPictureImage:placeholderImage];

    MPParserImageMsg *picMsgModel = [MPParserImageMsg yy_modelWithJSON:model.msg.receiveMsg];
    BOOL isOrigin = NO;
    if (picMsgModel) {
        isOrigin = picMsgModel.o;
    }

    BOOL exist = [[SDImageCache sharedImageCache] diskImageDataExistsWithKey:model.imgUrl];
    self.lookOriginBtn.hidden = YES;
    if (!exist && isOrigin) {
        if (![model.msg.msgFrom isEqualToString:WCICache.user.userId]) {
            self.lookOriginBtn.hidden = NO;
            NSString *strFileSize = [self imageSizeWithInteger:picMsgModel.s];
            NSString *btnTitle = [NSString stringWithFormat:@"%@(%@)",(@"查看原图"),strFileSize];
            CGSize titleS = [btnTitle sizeWithMaxWidth:SCREEN_WIDTH - 100 andFont:[UIFont systemFontOfSize:14]];
            CGRect frame = self.lookOriginBtn.frame;
            if (titleS.width > 120) {
                frame = CGRectMake(frame.origin.x, frame.origin.y, titleS.width, 32);
                self.lookOriginBtn.frame = frame;
            }

            [self.lookOriginBtn setTitle:btnTitle forState:UIControlStateNormal];
        }
    }
//    [MOXLogUntil LogNomalWithString:@"---------- model.image = %@   ---- exist = %@  ----- url = %@",model.image,exist?@"yes":@"no",model.imgUrl];

    if (model.image && exist && ![[model.imgUrl pathExtension]containsString:@"gif"]){
        imageView.image = model.image;
        if (exist) {
            imageView.image = [[SDImageCache sharedImageCache] imageFromCacheForKey:model.imgUrl];
            model.image = [[SDImageCache sharedImageCache] imageFromCacheForKey:model.imgUrl];

        }
        [self setPictureImage:model.image];
        NSString * fileKey = model.msg ? model.msg.fileKey :model.imgUrl;
        [[ICMediaManager sharedManager] updatePhotoCacheWithPath:fileKey WithImage:model.image];
        if (self.callBackToLoadImageEnd) {
            self.callBackToLoadImageEnd(model.image, self.cellIndex);
        }

    } else {
        BOOL smallExist = [[SDImageCache sharedImageCache] diskImageDataExistsWithKey:model.imgUrl];
        if (isOrigin && !smallExist) {
            if (![model.msg.msgFrom isEqualToString:WCICache.user.userId]) {
                self.aiView.hidden = NO;
                [self.aiView startAnimating];
            }
            double date_s = CFAbsoluteTimeGetCurrent();
            [UIImage loadImage:[NSURL URLWithString:model.imgUrl] completion:^(UIImage *img, NSError *error) {
                self.aiView.hidden = YES;
                [self.aiView stopAnimating];
                double date_current1 = CFAbsoluteTimeGetCurrent() - date_s;
                NSLog(@"Time:---------000000----sd_setImageWithURL----------------- %f ms ======-----",date_current1 * 1000);
                imageView.image = img;
                if(!error){
                    [[SDImageCache sharedImageCache] storeImage:img forKey:[NSString stringWithFormat:@"%@_small",model.imgUrl] completion:nil];
                    
                    [self setPictureImage:img];
                    [self mo_photoLoadFinishWithMsg:model.msg withImgUrl:model.imgUrl image:img];
                    double date_current1 = CFAbsoluteTimeGetCurrent() - date_s;
                    NSLog(@"Time22222:---------000000----sd_setImageWithURL----------------- %f ms ======-----",date_current1 * 1000);
                    if (self.callBackToLoadImageEnd) {
                        self.callBackToLoadImageEnd(img, self.cellIndex);
                    }
                } else {
                    double date_current1 = CFAbsoluteTimeGetCurrent() - date_s;
                    NSLog(@"Time33333:---------000000----sd_setImageWithURL----------------- %f ms ======-----",date_current1 * 1000);
                    if (error.code != 2002) {
                        WCIToast.showMsg(netErrorTipString);
                    }
                }
            }];
        }
        if(model.imgUrl.length && !isOrigin) {
            if (![model.msg.msgFrom isEqualToString:WCICache.user.userId]) {
                self.aiView.hidden = NO;
                [self.aiView startAnimating];
            }
            double date_s = CFAbsoluteTimeGetCurrent();
            
            [UIImage loadImage:[NSURL URLWithString:model.imgUrl] completion:^(UIImage *img, NSError *error) {
                self.aiView.hidden = YES;
                [self.aiView stopAnimating];
                imageView.image = img;
                double date_current1 = CFAbsoluteTimeGetCurrent() - date_s;
                NSLog(@"Time:----------11111---sd_setImageWithURL------------------ %f ms ======--image datalen = %ld---",date_current1 * 1000,img.sd_imageData.length);
                
                if(!error){
                    //                    NSLog(@" req url = %@  ------ imageURL.absoluteString = %@",model.imgUrl,imageURL.absoluteString);
                    
                    if ([model.imgUrl isEqualToString:[NSURL URLWithString:model.imgUrl].absoluteString]) {
                        
                        [self setPictureImage:img];
                        [self mo_photoLoadFinishWithMsg:model.msg withImgUrl:model.imgUrl image:img];
                        if (self.callBackToLoadImageEnd) {
                            self.callBackToLoadImageEnd(img, self.cellIndex);
                        }
                    }
                } else {
                    if ([model.imgUrl isEqualToString:[NSURL URLWithString:model.imgUrl].absoluteString]) {

                        if (error.code != 2002) {
                            WCIToast.showMsg(netErrorTipString);
                        }
                    }
                }
            }];
            
        }
        
    }
    if (model.imgUrl.length && !exist && [model.msg.msgFrom isEqualToString:WCICache.user.userId]) {
        double date_s = CFAbsoluteTimeGetCurrent();
        [UIImage loadImage:[NSURL URLWithString:model.imgUrl] completion:^(UIImage *img, NSError *error) {
            self.aiView.hidden = YES;
            
            double date_current1 = CFAbsoluteTimeGetCurrent() - date_s;
            NSLog(@"Time:---------333333----sd_setImageWithURL------------------ %f ms ======-----",date_current1 * 1000);
            imageView.image = img;
            [self.aiView stopAnimating];
            if(!error){
                //                NSLog(@" req url = %@  ------ imageURL.absoluteString = %@",model.imgUrl,imageURL.absoluteString);
                
                if ([model.imgUrl isEqualToString:[NSURL URLWithString:model.imgUrl].absoluteString]) {
                    [self setPictureImage:img];
                    [self mo_photoLoadFinishWithMsg:model.msg withImgUrl:model.imgUrl image:img];
                    if (self.callBackToLoadImageEnd) {
                        self.callBackToLoadImageEnd(img, self.cellIndex);
                    }
                }
            } else {
                if ([model.imgUrl isEqualToString:[NSURL URLWithString:model.imgUrl].absoluteString]) {
                    if (error.code != 2002) {
                        WCIToast.showMsg(netErrorTipString);
                    }
                }
            }
        }];
    }
}

- (void)setPictureImage:(UIImage *)image {

    [UIView animateWithDuration:0.3 animations:^{
        self.pictureImageScrollView.contentOffset = CGPointMake(0, 0);
        self.pictureImageScrollView.zoomScale = 1.0f;
    }];
}

- (void)mo_photoLoadFinishWithMsg:(QAMessage *)msg withImgUrl:(NSString *)imgUrl image:(UIImage *)img {
    MPParserImageMsg *picMsgModel = [MPParserImageMsg yy_modelWithJSON:msg.receiveMsg];
    NSString *msgUrl = msg.receiveMsg;
    if (picMsgModel) {
        msgUrl = picMsgModel.url;
    }
    if ([[msgUrl lastPathComponent] isEqualToString:[imgUrl lastPathComponent]]) {
        ICMediaManager *manager = [ICMediaManager sharedManager];
        NSData *imgData = UIImageJPEGRepresentation(img, 1);
        NSString *stringPath = [manager imagePathWithFileKey:msg.fileKey];
        [manager updatePhotoCacheWithPath:msg.fileKey WithImage:img];
        [imgData writeToFile:stringPath atomically:YES];
        if (imgUrl.length > 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadOneCell" object:@{@"message":@"",@"contentType":@(1022),@"imageUrl":imgUrl}];
        }
    }
}

- (void)prepareForReuse {
    [super prepareForReuse];
    //在下面写取消下载的操作。
    UIImageView *imageV = _pictureImageScrollView.zoomImageView;
    imageV.contentMode = UIViewContentModeScaleAspectFit;
    imageV.clipsToBounds = YES;
    [imageV sd_cancelCurrentImageLoad];// sd_cancelCurrentAnimationImagesLoad];//如果用了SDWebImageDownloaderOperation，就取消这个SDWebImageDownloaderOperation。
}
- (CGSize)backImageSize:(UIImage *)image {
    
    CGSize size = image.size;
    CGSize newSize;
    newSize.width = self.pictureImageScrollView.width;
    newSize.height = newSize.width / size.width * size.height;
    if (self.pictureImageScrollView.width > self.pictureImageScrollView.height) {
        newSize.height = self.pictureImageScrollView.height;
        newSize.width = newSize.height / size.height * size.width;
    }
    return newSize;
    
//    CGSize imageSize = image.size;
//    double imgRadio = image.size.width/image.size.height;
//    if (imgRadio > 1) {
//        //宽 > 高
//        imageSize.width = SCREEN_WIDTH;
//        if (imgRadio > 2) {
//            // 超宽图片
//            imageSize.height = imageSize.width /2;
//        } else {
//            imageSize.height = imageSize.width /imgRadio;
//        }
//    } else {
//        imageSize.height = SCREEN_HEIGHT;
//        if (imgRadio < 0.3) {
//            //超高图
//            imageSize.width = (SCREEN_WIDTH /SCREEN_HEIGHT) * imageSize.height;
//        } else {
//            imageSize.width = imgRadio * imageSize.height;
//        }
//    }
//
//    return imageSize;

}


// 获取指定视图在window中的位置
- (CGRect)getFrameInWindow:(UIView *)view {
    return [view convertRect:view.bounds toView:[UIApplication sharedApplication].keyWindow];
}

#pragma mark - 旋转

- (void)onDeviceOrientationChangeWithObserver {
    [self onDeviceOrientationChange];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeviceOrientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];
}

-(void)onDeviceOrientationChange {
//    if (!self.isNeedLandscape) {
//        return;
//    }
    
    
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
//    self.orientation = orientation;
    if (UIDeviceOrientationIsLandscape(orientation)) {
        if (self.bounds.size.width < self.bounds.size.height) {
            [_pictureImageScrollView setZoomScale:1.0 animated:YES];//还原
        }
        [UIView animateWithDuration:10.3 delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            self.transform = (orientation==UIDeviceOrientationLandscapeRight)?CGAffineTransformMakeRotation(M_PI*1.5):CGAffineTransformMakeRotation(M_PI/2);
            if (iPhoneX) {
                self.center = [UIApplication sharedApplication].keyWindow.center;
                self.bounds = CGRectMake(0, 0,  SCREEN_HEIGHT - WCI_IPHONE_STATUSBAR_HEIGHT - WCI_IPHONE_SAFEBOTTOMAREA_HEIGHT, SCREEN_WIDTH);
            } else {
                self.bounds = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
            }
            [self setNeedsLayout];
            [self layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
        
    }else if (orientation==UIDeviceOrientationPortrait){
        if (self.bounds.size.width > self.bounds.size.height) {
            [_pictureImageScrollView setZoomScale:1.0 animated:YES];//还原
        }
        [UIView animateWithDuration:10.3 delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            self.transform = (orientation==UIDeviceOrientationPortrait)?CGAffineTransformIdentity:CGAffineTransformMakeRotation(M_PI);
            self.bounds = CGRectMake(0, 0, SCREEN_WIDTH + 50, SCREEN_HEIGHT);

            [self setNeedsLayout];
            [self layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
        
    }
}


- (void)updateImageLayoutWithOrientation:(UIDeviceOrientation)orientation previousImageSize:(CGSize)previousImageSize {
    
        self.pictureImageScrollView.zoomScale = 1;

    NSLog(@"orientation = %ld",orientation);
    if (UIDeviceOrientationIsLandscape(orientation)) {
        self.pictureImageScrollView.frame = CGRectMake(0, 0,SCREEN_HEIGHT ,SCREEN_WIDTH );
    } else if (orientation == UIDeviceOrientationPortrait) {
        self.pictureImageScrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }

    [self setPictureImage:self.pictureImageScrollView.zoomImageView.image];
}



#pragma mark --

- (void)downloadOriginImage:(UIButton *)sender {
    UIImageView *imageView = _pictureImageScrollView.zoomImageView;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.clipsToBounds = YES;
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.model.imgUrl] placeholderImage:imageView.image options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        NSLog(@"receivedSize = %ld   expectedSize = %ld",receivedSize,expectedSize);
        double dPer = ((double)receivedSize/(double)(expectedSize))*100;
        if (dPer > 0) {
            NSString *per = [NSString stringWithFormat:@"%.0f%@",dPer,@"%"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [sender setTitle:per forState:UIControlStateNormal];
            });
        }
    } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        dispatch_async(dispatch_get_main_queue(), ^{
            sender.hidden = YES;
            self.aiView.hidden = YES;
            [self.aiView stopAnimating];

            if(!error){
                if ([self.model.imgUrl isEqualToString:imageURL.absoluteString]) {
                    
                    [self setPictureImage:image];
                    [self mo_photoLoadFinishWithMsg:self.model.msg withImgUrl:self.model.imgUrl image:image];
                    if (self.callBackToLoadImageEnd) {
                        self.callBackToLoadImageEnd(image, self.cellIndex);
                    }
                }
            } else {
                if ([[NSString stringWithFormat:@"%@?x-oss-process=image/resize,p_70",self.model.imgUrl] isEqualToString:imageURL.absoluteString]) {
                    UIImage *img = [UIImage imageNamed:@"new_img_loading"];
                    [[SDImageCache sharedImageCache] storeImage:img forKey:[NSString stringWithFormat:@"%@_small",self.model.imgUrl] completion:nil];
                    
                    [self setPictureImage:img];
                    [self mo_photoLoadFinishWithMsg:self.model.msg withImgUrl:self.model.imgUrl image:img];
                    if (self.callBackToLoadImageEnd) {
                        self.callBackToLoadImageEnd(img, self.cellIndex);
                    }
                }
                WCIToast.showMsg(netErrorTipString);
            }
        });
    }];
}


- (NSString *)imageSizeWithInteger:(NSUInteger)integer {
    CGFloat size = integer/1024.0;
    if ( size > 1000.0) { // 1000kb不好看，所以我就以1000为标准了
        return [NSString stringWithFormat:@"%.1fM",size/1024.0];
    } else {
        return [NSString stringWithFormat:@"%.0fK",size];
    }
}

@end
